from flask import Flask, session, redirect, url_for, request, render_template_string

app = Flask(__name__)
# 设置密钥，用于加密 session 数据
app.secret_key = 'your_secret_key'

# 定义一个简单的HTML模板，用于显示登录状态和session ID
HTML = '''
<html>
<body>
    {% if session.username  %}
        <p>Logged in as {{ session.username  }}</p> 
        <a href="{{ url_for('logout') }}">Logout</a> 
    {% else %} 
        <p>Not logged in</p> 
        <form action="{{ url_for('login') }}" method="post"> 
            <label for="username">Username:</label> 
            <input type="text" id="username" name="username" required> 
            <br> 
            <button type="submit">Login</button> 
        </form> 
    {% endif %} 
</body>
</html>
'''

@app.route('/')
def index():
    # 检查用户是否已经登录
    print(f'cookies: {request.cookies}')
    return render_template_string(HTML, session=session)

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        # 获取用户输入的用户名
        session['username'] = request.form['username']
        print(session['username'])
        return redirect(url_for('index')),302
    return render_template_string(HTML, session=session)

@app.route('/logout')
def logout():
    # 清除用户的 session 数据
    session.pop('username', None)
    return redirect(url_for('index'))

if __name__ == '__main__':
    app.run(debug=True)
